<template>
  <view class="container">
    <view class="wechatapp">
      <view class="header">
        <!-- <open-data class="avatar" type="userAvatarUrl"></open-data> -->
        <image class="image" src="/static/user/logo.png"></image>
      </view>
	  
    </view>
    <view class="auth-title" >申请成为代理商</view>
    <!-- <view class="auth-subtitle">获得你的公开信息（昵称、头像等）</view> -->
	<view class="login-view">
		<u-form :model="form" ref="uForm" >
				<u-form-item label="" prop="mobile" left-icon="phone"  :label-style="{'font-size': '34rpx','font-weight': 'bold'}" :left-icon-style="{'font-size': '40rpx'}">
					<u-input v-model="form.mobile"  placeholder="请输入手机号" style="font-size: 30rpx;"/>
				</u-form-item>
				<u-form-item label="" prop="name" left-icon="account"  :label-style="{'font-size': '34rpx','font-weight': 'bold'}" :left-icon-style="{'font-size': '40rpx'}">
					<u-input v-model="form.name"  placeholder="请输入姓名" style="font-size: 30rpx;"/>
				</u-form-item>
				<u-form-item label="" prop="password" left-icon="lock"  :label-style="{'font-size': '34rpx','font-weight': 'bold'}" :left-icon-style="{'font-size': '40rpx'}">
					<u-input v-model="form.password" type="password" :adjust-position="false" placeholder="请输入密码" style="font-size: 30rpx;"/>
				</u-form-item>
				
				<u-form-item label="" prop="code" left-icon="integral"  :label-style="{'font-size': '34rpx','font-weight': 'bold'}" :left-icon-style="{'font-size': '40rpx'}">
					<u-input v-model="form.code" type="number" placeholder="手机验证码" style="font-size: 30rpx;"/>
				    <u-button class="btstyle" @click="gocode" :disabled="disabled">{{bttest}}</u-button>
					<!-- <input type="text" > -->
				</u-form-item>
				
			</u-form>
	</view>
	
    <view class="login-btn">
	  <u-button  shape="circle" @click="goregister"  class="button btn-normal">提交申请</u-button>
    
    </view>
   <!-- <view class="no-login-btn">
	  <u-button  shape="circle"   class="button btn-normal">暂不登录</u-button>
    </view> -->
	<!-- <view class="login-test">
		<view class="login-item">
			<view class="login-icom">
				<u-icon name="plus-circle" class="login-icoms" color="#000000" size="80"></u-icon>
			</view>
			
			<text class="login-text">注册</text>
		</view>
		<view class="login-item">
			<view class="login-icom">
				<u-icon name="lock-open" class="login-icoms" color="#000000" size="80"></u-icon>
			</view>
			
			<text class="login-text">忘记密码</text>
			
		</view>
		
	</view> -->
  </view>
</template>

<script>
import { agentApply } from "@/api/agent";
import { sendUserCode } from "@/api/login/login";

const app = getApp();
export default {
  data() {
    return {
      value: false,
      // 商城基本信息
      storeInfo: undefined,
      // 微信小程序登录凭证 (code)
      // 提交到后端，用于换取openid
      code: "",
	  form:{
		  token:'',
		  mobile:'',
		  code:'',
		  password:'',
		  name:'',
		  },
      list: [
        {
          name: "注册",
          checked: false,
          disabled: false,
        },
      ],
	  bttest:"获取验证码",
	  disabled:false,
	  times:60,
	  //定时器
	  intetime:null,
	  mobile:'',
	  rules: {
	  	// 字段名称
	  	mobile: [
	  		{
	  			required: true, 
	  			message: '请输入手机号',
	  			trigger: ['change','blur'],
	  		},
	  		{
	  			// 自定义验证函数，见上说明
	  			validator: (rule, value, callback) => {
	  				// 上面有说，返回true表示校验通过，返回false表示不通过
	  				// this.$u.test.mobile()就是返回true或者false的
	  				return this.$u.test.mobile(value);
	  			},
	  			message: '手机号码不正确',
	  			// 触发器可以同时用blur和change
	  			trigger: ['change','blur'],
	  		}
	  	],
		code: [
							{ 
								required: true, 
								message: '请输入验证码', 
								// 可以单个或者同时写两个触发验证方式 
								trigger: ['change','blur'],
							}
						],
		password: [
							{ 
								required: true, 
								message: '请输入密码', 
								// 可以单个或者同时写两个触发验证方式 
								trigger: ['change','blur'],
							}
						],
		name: [
							{ 
								required: true, 
								message: '请输入姓名', 
								// 可以单个或者同时写两个触发验证方式 
								trigger: ['change','blur'],
							}
						],
	    
	 }	
    };
  },

  created() {},
  beforeDestroy() {
	  clearInterval(this.intetime)
    if (!uni.getStorageSync("userId")) {
      uni.removeStorageSync("userId");
      uni.removeStorageSync("mobile");
    }
  },
  onLoad() {
	  
var sjs=this.randomWord()
	      var datatime = Date.parse(new Date());
	      var tokens=''+sjs+''+datatime
		  this.form.token=tokens
		  
		  
  },
  onReady() {
  		this.$refs.uForm.setRules(this.rules);
  	},
  methods: {
	  randomWord() {
	      var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
	       var nums = "";
	        for (var i = 0; i < 20; i++) {
	        var id = parseInt(Math.random() * 61);
	        nums += chars[id]
	        }
	        return nums; 
	        },
	
	 async goregister(){
		  // code:'',
		  // password:'',
		  // againPassword:'',
		  let tjshow=true
		 
		 
		  
		  
		 this.$refs.uForm.validate(valid => {
		 				if (valid) {
		 					tjshow=true
		 				} else {
		 					
							tjshow=false
		 				}
		 			});
					
			if(!tjshow){
				return
			}
			
					
			let Registe=  await agentApply(JSON.stringify(this.form))
			if(Registe.result==0){
						 uni.showToast({
						   title: Registe.message,
						   icon: "success",
						   duration: 2000,
						 });
					
						 
						 
			}else{
						
						 var sjs=this.randomWord()
						 var datatime = Date.parse(new Date());
						 var tokens=''+sjs+''+datatime
						 this.form.token=tokens
						
						  uni.showToast({
						  	icon:"none",
						  	title:Registe.message
						  })
						   
			 }		
		 
		 
		 
		  
	  },
	 async gocode(){
		 let that=this
		 if(this.form.mobile==""){
			 uni.showToast({
			 	icon:"none",
			 	title:"请填写手机号"
			 })
			 return
		 }
		  var data={
			  mobile:this.form.mobile
		  };
		  
		  let Code=await sendUserCode(JSON.stringify(data))
		  
		  
		  if(Code.result==0){
			  this.bttest="60s"
			  this.disabled=true
			 that.times=60
			  that.intetime=setInterval(()=>{
				  that.times=that.times-1
				  that.bttest=that.times+'s'
				  console.log(that.times)
				  
				  if(that.times<=0){
					  clearInterval(that.intetime)
					  this.disabled=false
					  this.bttest="获取验证码"
				  }
			  },1000)
			  uni.showToast({
			  	icon:"none",
			  	title:"验证码发送成功"
			  })
		  }else{
			  uni.showToast({
			  	icon:"none",
			  	title:Code.message
			  })
		  }
		  
	  },
    // 选中某个复选框时，由checkbox时触发
    checkboxChange(e) {
      console.log(e, "123");
      this.value = e.value;
      console.log(this.value, "value");
    },
    // 选中任一checkbox时，由checkbox-group触发
    checkboxGroupChange(e) {
      console.log(e, "345");
    },

    //用户登录凭证code
    getCode() {
      const than = this;
      return new Promise((resolve, reject) => {
        uni.login({
          provider: "weixin",
          success: (res) => {
            console.log(res.code, "res code");
            resolve(res.code);
          },
          fail: reject,
        });
      });
    },

    async getPhoneNumber(e) {
      console.log(e, "eee");
      console.log(e.detail.code, "e 手机code");
      const code = await this.getCode();
      console.log(code, "登录用得code");
      const app = this;
      if (e.detail.code) {
        const data = {
          phoneCode: e.detail.code,
          wxOpenIdCode: code,
          parentInviteCode: uni.getStorageSync("parentInviteCode") || "",
        };
        //登录接口
        const logoData = await wxLoginApi(data);
        console.log(logoData, "提交到后端登录接口");
        if (logoData.code === 0) {
          uni.showToast({
            title: "登录成功",
            icon: "success",
            duration: 2000,
          });
          // 获取到的当前数据存入缓存
          const { wxToken, openId, userInfo } = logoData.data;
          uni.setStorageSync("token", wxToken);
          uni.setStorageSync("openId", userInfo.wxOpenid);
          uni.setStorageSync("userInfoServer", userInfo);
          uni.setStorageSync("phoneNumber", userInfo.phone);
          uni.setStorageSync("userId", userInfo.userId);
          setTimeout(() => {
            app.handleCancel();
          }, 1500);
        } else {
          uni.showToast({
            title: "登录失败",
            icon: "success",
            duration: 2000,
          });
          setTimeout(() => {
            app.handleCancel();
          }, 1500);
        }
      }
    },

    // getUserProfile() {
    //   uni.showLoading({
    //     title: "加载中...",
    //   });
    //   //获取用户信息 包含appid
    //   // const appid = uni.getAccountInfoSync();
    //   // console.log(appid, "appid");
    //   const app = this;
    //   console.log("登录授权开始");
    //   wx.canIUse("getUserProfile") &&
    //     wx.getUserProfile({
    //       lang: "zh_CN",
    //       desc: "获取用户相关信息",
    //       async success(res) {
    //         console.log("用户同意了授权");
    //         console.log("用户信息:", res);
    //         // const { encryptedData, iv } = res;
    //         const {
    //           gender,
    //           avatarUrl,
    //           city,
    //           country,
    //           language,
    //           nickName,
    //           province,
    //         } = res.userInfo;
    //         uni.setStorageSync("MyUserInfo", res.userInfo);
    //         // const code = await app.getCode();
    //         uni.login({
    //           provider: "weixin",
    //           success: async (codeData) => {
    //             // app.data.encryptedData = encryptedData;
    //             // app.data.iv = iv;
    //             const data = {
    //               code: codeData.code,
    //               // wxEncryptInfo: {
    //               //   encryptedData: app.trimAll(encryptedData),
    //               //   iv,
    //               // },
    //               memberInfo: {
    //                 avatarUrl: avatarUrl || "",
    //                 city: city || "",
    //                 country: country || "",
    //                 gender: gender || "",
    //                 language: language || "",
    //                 nickName: nickName || "",
    //                 province: province || "",
    //               },
    //               parentInviteCode: uni.getStorageSync("parentInviteCode") || "",
    //             };
    //             //登录接口
    //             const logoData = await getLogin(data);
    //             console.log(logoData, "提交到后端登录接口");
    //             if (logoData.code === 0) {
    //               uni.hideLoading();
    //               uni.showToast({
    //                 title: "登录成功",
    //                 icon: "success",
    //                 duration: 2000,
    //               });
    //               // 获取到的当前数据存入缓存
    //               const { wxToken, openId, userInfo } = logoData.data;
    //               uni.setStorageSync("token", wxToken);
    //               uni.setStorageSync("openId", userInfo.wxOpenid);
    //               uni.setStorageSync("userInfoServer", userInfo);
    //               uni.setStorageSync("phoneNumber", userInfo.phone);
    //               uni.setStorageSync("userId", userInfo.userId);
    //               setTimeout(() => {
    //                 app.handleCancel();
    //               }, 1500);
    //               return true;
    //             } else {
    //               uni.showToast({
    //                 title: "登录失败",
    //                 icon: "success",
    //                 duration: 2000,
    //               });
    //               setTimeout(() => {
    //                 app.handleCancel();
    //               }, 1500);
    //             }
    //           },
    //           fail: (err) => {
    //             console.log(err, "登录错误");
    //           },
    //         });
    //       },
    //       fail() {
    //         console.log("用户拒绝了授权");
    //       },
    //     });
    // },

    // async getPhoneNumber(e) {
    //   console.log(e,'eee')
    //   console.log(e.detail.code, "e 手机code");
    //   const code=await this.getCode()
    //   console.log(code,'登录用得code')
    //   //这里获取code
    //   return;
    //   if (e.detail.code) {
    //     //获取手机号
    //     const getPhoneData = await getPhone(e.detail.code);
    //     if (getPhoneData.code === 0) {
    //       const { phoneNumber } = getPhoneData.data.phone_info;
    //       uni.setStorageSync("phoneNumber", phoneNumber);
    //       uni.showToast({
    //         title: "授权成功",
    //         icon: "success",
    //         duration: 2000,
    //       });
    //       setTimeout(() => {
    //         this.handleCancel();
    //       }, 1500);
    //     } else {
    //       uni.showToast({
    //         title: "授权失败",
    //         icon: "error",
    //         duration: 2000,
    //       });
    //     }
    //   }
    // },

    /**
     * 暂不登录
     */
    handleCancel() {
      // 跳转回原页面
      uni.navigateBack({
        delta: 1,
      });
    },

    /**
     * 登录成功-跳转回原页面
     */
    // onNavigateBack(delta = 1) {
    //   const pages = getCurrentPages();
    //   if (pages.length > 1) {
    //     uni.navigateBack({
    //       delta: Number(delta || 1),
    //     });
    //   } else {
    //     uni.navigateBack({
    //       delta: 1,
    //     });
    //   }
    // },
  },
};
</script>

<style lang="scss" scoped>
	.btstyle{
		width: 165rpx;
		background: #fc3100;
		color: white;
	}
u-checkbox-group::v-deep {
  .u-checkbox__label {
    margin-right: rpx(0);
  }
}

.checkBox_wrapper {
  font-size: rpx(12);
  display: flex;
}

.container {
  padding: 0 60rpx;
  font-size: 32rpx;
  background: #fff; 
  min-height: 100vh;
}
.login-test{
	margin-top: rpx(20);
	
	display: flex;
	justify-content: center;
	.login-item{
		width: rpx(80);
		height: rpx(80);
		text-align: center;
		margin-left: rpx(20);
		margin-right: rpx(20);
		.login-text{
			width: 100%;
			font-size: rpx(15);
			line-height: rpx(35);
		}
		.login-icom{
			// width: rpx(48);
			// height: rpx(48);
			// border-radius: 50%;
			// border: rpx(3) solid black;
			// margin: 0 auto;
			.login-icoms{
			
			}
		}
	}
}

.wechatapp {
  padding: 80rpx 0 48rpx;
  //border-bottom: 1rpx solid #e3e3e3;
  margin-bottom: 72rpx;
  text-align: center;

  .header {
    width: 190rpx;
    height: 190rpx;
    border: 4rpx solid #fff;
    margin: 0 auto 0;
    border-radius: 50%;
    overflow: hidden;
    box-shadow: 2rpx 0 10rpx rgba(50, 50, 50, 0.3);
	

    .image {
      display: block;
      width: 100%;
      height: 100%;
    }
  }
}

.auth-title {
  color: #585858;
  font-size: 34rpx;
  margin-bottom: 40rpx;
}

.auth-subtitle {
  color: #888;
  margin-bottom: 88rpx;
  font-size: 28rpx;
}
.login-view{
	width: 100%;
	box-sizing: border-box;
	padding: 0 rpx(20);
}

.login-btn {
  //padding: 0 20rpx;
  box-sizing: border-box;
  padding: 0 rpx(20);
  margin-bottom: rpx(13);
  margin-top: rpx(13);

  .button {
    height: 88rpx;
    //background: #04be01;
    color: #fff;
    background: #fc3100;
    font-size: 30rpx;
    // border-radius: rpx(5);	
	font-weight: bold;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}


.no-login-btn {
	box-sizing: border-box;
	padding: 0 rpx(20);
  margin-top: 20rpx;
  //padding: 0 20rpx;

  .button {
    height: 88rpx;
    background: #dfdfdf;
    color: #fff;
    font-size: 30rpx;
    // border-radius: rpx(5);
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
